//
//  UserAccount.swift
//  Weibo(Swift)
//
//  Created by 阳 on 16/7/13.
//  Copyright © 2016年 阳. All rights reserved.
//

import UIKit
let userAccountKey = "userAccountKey"
class UserAccount: NSObject {

   
    static let shareUserAccount = UserAccount()
    
    var access_token : String?
    
    var expires_date : NSDate?
    
    var expires_in : NSTimeInterval = 0 {
        didSet {
            expires_date = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    var screen_name : String?
    var avatar_large :String?
    var uid : String?
    var isExpires : Bool {
        
        return expires_date?.compare(NSDate()) == NSComparisonResult.OrderedAscending
    }
    var isLogin : Bool {
//        print(access_token)
//        NSHomeDirectory()
        return access_token != nil && !isExpires
    }
    /// 当前的类的描述信息,建议所有的模型类都要实现该属性,方便调试. 当我们print当前类的对象时,会打印description的值.
    override var description: String{
        return dictionaryWithValuesForKeys(["access_token","expires_date","expires_in","screen_name","avatar_large","uid"]).description
     
    }
    
    
    override init() {
        super.init()
        loadUserAccount()
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    func loadUserAccount()
    {
        let userAccount = NSUserDefaults.standardUserDefaults().objectForKey(userAccountKey)
        
        if let dic = userAccount as? [String : AnyObject]
        {
            setValuesForKeysWithDictionary(dic )
        }
    }
    func saveUserAccount(dic: [String : AnyObject])
    {
        
        setValuesForKeysWithDictionary(dic)
        let userDic = dictionaryWithValuesForKeys(["screen_name", "access_token", "avatar_large", "uid", "expires_date"])
        NSUserDefaults.standardUserDefaults().setObject(userDic, forKey: userAccountKey)
    }
}
